package CompletableFuture_14;

import java.util.concurrent.*;
import java.util.function.*;

public class 异常处理示例_handle_exceptionally {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 创建10个可能失败的任务 - 使用Supplier
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            CompletableFuture.supplyAsync(new Supplier<String>() {
                        public String get() {
                            try {
                                Thread.sleep((long)(Math.random() * 300));
                                if (Math.random() > 0.7) {
                                    throw new RuntimeException("任务" + taskId + "模拟失败");
                                }
                                return "任务" + taskId + "成功";
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }, executor)
                    .handle(new BiFunction<String, Throwable, String>() {
                        public String apply(String result, Throwable throwable) {
                            if (throwable != null) {
                                return "处理失败: " + throwable.getMessage();
                            }
                            return "处理成功: " + result;
                        }
                    })
                    .thenAccept(new Consumer<String>() {
                        public void accept(String s) {
                            System.out.println(s);
                        }
                    });
        }

        executor.shutdown();
    }
}